import { types, flow, addDisposer } from 'mobx-state-tree';
import { when, reaction } from 'mobx';
import { history } from './RouterAndHistory';
import { Toast } from 'antd-mobile';

function sleep(s?: number): Promise<number> {
  return new Promise(r => setTimeout(() => r(s ?? -1), s ?? 900));
}

export const Model = types.model('Model', {
  count: 0,
}).volatile(self => {
  return {
    initialCount: self.count,
  };
}).views(self => {
  return {
    get unsaved(): boolean {
      return self.count !== self.initialCount;
    },
  }
}).actions(self => {
  function increase() {
    self.count++;
  }
  return {
    increase,
    doFlow: flow(function* () {
      console.log(yield sleep());
      increase();
      console.log(yield sleep());
      increase();
      console.log(yield sleep());
      increase();
    }),
    commit: flow(function* () {
      // save to server
      yield sleep();
      // 恢复表单状态为初始状态
      self.count = self.initialCount;
      Toast.show({ content: '表单保存成功' });
    }),
    afterCreate() {
      addDisposer(self, reaction(() => self.unsaved, (unsaved) => {
        if (unsaved) {
          const closeBlock = history.block('存在未保存内容，是否离开当前页面？');
          addDisposer(self, when(() => !self.unsaved, () => {
            closeBlock();
          }));
        }
      }));
    }
  }
});